package com.qysoft.modules.common.action;

import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.qysoft.modules.xxwh.service.RYGLService;
import com.qysoft.modules.xxwh.service.ZYGLService;
import com.qysoft.rapid.actions.RapidAction;
import com.qysoft.rapid.core.RapidDbConn;
import com.qysoft.rapid.domain.Bean;
import com.qysoft.rapid.domain.CurrentRyxx;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * 首页控制层
 * @author liugong
 *
 */
public class MainAction extends RapidAction {
	
	public void index() throws Exception{
		redirect("/main");
	}
	
	/**
	 * 首页
	 * @throws Exception 
	 */
	@Before(RapidDbConn.class)
	public void main() throws Exception{
		//主菜单数据
		String ryid = getCurrentRyxx().getStr("id");
		List<Bean> yjzyList = ZYGLService.queryZyljForMain(ryid);
		setAttr("yjzyList", yjzyList);
		//当前登录人数据
		bindCurrentRyxxToPage();
		renderJsp("/WEB-INF/index.jsp");
	}
	
	/**
	 * 主跳转
	 */
	public void jump(){
		renderJsp("/WEB-INF/pages/common/jump.jsp");
	}
	
	/**
	 * 跳转至登陆
	 */
	public void login(){
		renderJsp("/WEB-INF/pages/common/login.jsp");
	}
	
	/**
	 * 验证登陆
	 */
	@Before(RapidDbConn.class)
	public void validateLogin(){
		//获取表单提交的用户名和密码
		String username = getPara("username").trim();;
		String password = getPara("password").trim();
		//绑定登陆凭证
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		//获取当前用户
		Subject subject = SecurityUtils.getSubject();
		//执行登陆
		try {
			subject.login(token);
			CurrentRyxx currentRyxx = RYGLService.queryCurrnetRyxxByDm(username);
			setSessionAttr("currentRyxxJson", JsonKit.toJson(currentRyxx));
			setSessionAttr("currentRyxx",currentRyxx);
		} catch (Exception e) {
			e.printStackTrace();
			setAttr("username", username);
			setAttr("password", password);
			setAttr("error", e.getMessage());
			forwardAction("/login");
			return;
		}
		redirect("/main");
	}
	
	/**
	 * 登出操作
	 */
	public void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
		redirect("/jump");
	}
	
}
